"""
HDF5主窗口UI类
包含所有用户界面元素的创建和布局，专为HDF5数据设计
"""

from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QGridLayout, QGroupBox, QCheckBox, QRadioButton, QComboBox, 
                             QLineEdit, QPushButton, QLabel, QFileDialog, QMessageBox, 
                             QButtonGroup, QTreeWidget, QTreeWidgetItem, QSpinBox,
                             QSplitter, QScrollArea, QApplication)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer
import os
import config


class MainWindow(QMainWindow):
    """主窗口类，负责UI的创建和管理"""
    
    # 定义信号
    file_loaded = pyqtSignal(str)  # 文件加载信号
    plot_requested = pyqtSignal(dict)  # 绘图请求信号
    preview_requested = pyqtSignal()  # 预览请求信号
    sorting_requested = pyqtSignal() # 自动排序请求信号
    
    def __init__(self):
        super().__init__()
        self.current_file_path = None
        self.amp_phase_pairs = []
        self.original_pairs_order = []  # 保存原始顺序
        self.init_ui()
        
    def init_ui(self):
        """初始化用户界面"""
        # 使用 QApplication 中设置的应用程序名称作为窗口标题
        app_name = QApplication.instance().applicationName()
        self.setWindowTitle(app_name)
        self.setGeometry(*config.APP_GEOMETRY)
        
        # 主布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QHBoxLayout(main_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)
        
        # 左侧：文件结构浏览器
        left_panel = self.create_file_browser_panel()
        splitter.addWidget(left_panel)
        
        # 右侧：控制面板
        right_panel = self.create_controls_panel()
        splitter.addWidget(right_panel)
        
        # 设置分割器比例
        splitter.setSizes([400, 600])
        
        # 创建菜单栏
        self.create_menu_bar()
        
    def create_file_browser_panel(self):
        """创建文件浏览器面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 文件加载组
        file_group = QGroupBox("HDF5文件")
        file_layout = QVBoxLayout()
        
        # 文件名显示
        self.filename_display = QLineEdit(config.DEFAULT_H5_FILENAME_DISPLAY)
        self.filename_display.setReadOnly(True)
        file_layout.addWidget(self.filename_display)
        
        # 加载按钮
        load_button = QPushButton("加载HDF5文件")
        load_button.clicked.connect(self.load_file)
        file_layout.addWidget(load_button)
        
        file_group.setLayout(file_layout)
        layout.addWidget(file_group)
        
        # 文件结构树
        tree_group = QGroupBox("文件结构")
        tree_layout = QVBoxLayout()
        
        self.file_tree = QTreeWidget()
        self.file_tree.setHeaderLabels(config.TREE_HEADERS)
        
        # 设置列宽
        for i, width in enumerate(config.TREE_COLUMN_WIDTHS):
            self.file_tree.setColumnWidth(i, width)
        
        tree_layout.addWidget(self.file_tree)
        tree_group.setLayout(tree_layout)
        layout.addWidget(tree_group)
        
        # 数据选择组
        selection_group = QGroupBox("数据选择")
        selection_layout = QVBoxLayout()
        
        # 自动查找配对按钮
        find_pairs_button = QPushButton("自动查找幅度-相位配对")
        find_pairs_button.clicked.connect(self.find_amp_phase_pairs)
        selection_layout.addWidget(find_pairs_button)
        
        # 排序控制按钮组
        sort_buttons_layout = QHBoxLayout()
        
        # 启用拖拽排序按钮
        self.enable_drag_sort_button = QPushButton("启用拖拽排序")
        self.enable_drag_sort_button.setCheckable(True)
        self.enable_drag_sort_button.clicked.connect(self.toggle_drag_sort)
        sort_buttons_layout.addWidget(self.enable_drag_sort_button)
        
        # 上移按钮
        self.move_up_button = QPushButton("↑ 上移")
        self.move_up_button.clicked.connect(self.move_pair_up)
        sort_buttons_layout.addWidget(self.move_up_button)
        
        # 下移按钮
        self.move_down_button = QPushButton("↓ 下移")
        self.move_down_button.clicked.connect(self.move_pair_down)
        sort_buttons_layout.addWidget(self.move_down_button)
        
        # 重置顺序按钮
        self.reset_order_button = QPushButton("重置顺序")
        self.reset_order_button.clicked.connect(self.reset_pairs_order)
        sort_buttons_layout.addWidget(self.reset_order_button)
        
        # 自动排序按钮
        self.auto_sort_button = QPushButton("自动排序")
        self.auto_sort_button.clicked.connect(self.auto_sort_pairs)
        sort_buttons_layout.addWidget(self.auto_sort_button)
        
        selection_layout.addLayout(sort_buttons_layout)
        
        # 配对列表
        self.pairs_tree = QTreeWidget()
        self.pairs_tree.setHeaderLabels(["数据对", "选择"])
        self.pairs_tree.setColumnWidth(0, 250)
        self.pairs_tree.setColumnWidth(1, 50)
        self.pairs_tree.setDragDropMode(QTreeWidget.InternalMove)
        self.pairs_tree.setAcceptDrops(True)
        self.pairs_tree.setDragEnabled(False)  # 默认禁用拖拽
        # 连接拖拽完成信号
        self.pairs_tree.model().rowsMoved.connect(self._on_pairs_reordered)
        selection_layout.addWidget(self.pairs_tree)
        
        selection_group.setLayout(selection_layout)
        layout.addWidget(selection_group)
        
        return panel
    
    def create_controls_panel(self):
        """创建控制面板"""
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setMaximumWidth(config.CONTROLS_PANEL_MAX_WIDTH)
        
        controls_widget = QWidget()
        controls_layout = QVBoxLayout(controls_widget)
        
        # 波形选择组
        self.create_waveform_selection_group(controls_layout)
        
        # 批量处理组
        self.create_batch_processing_group(controls_layout)
        
        # 绘图模式组
        grid_layout = QGridLayout()
        self.create_mode_group(grid_layout)
        self.create_plot_style_group(grid_layout)
        self.create_command_group(grid_layout)
        controls_layout.addLayout(grid_layout)
        
        # 参数设置组
        self.create_parameter_group(controls_layout)
        
        controls_layout.addStretch(1)
        scroll_area.setWidget(controls_widget)
        
        return scroll_area
    
    def create_waveform_selection_group(self, parent_layout):
        """创建波形选择组"""
        group = QGroupBox("波形选择")
        layout = QGridLayout()
        
        layout.addWidget(QLabel("波形索引:"), 0, 0)
        self.waveform_spinbox = QSpinBox()
        self.waveform_spinbox.setMinimum(0)
        self.waveform_spinbox.setMaximum(0)  # 将根据数据动态设置
        self.waveform_spinbox.setValue(config.DEFAULT_WAVEFORM_INDEX)
        layout.addWidget(self.waveform_spinbox, 0, 1)
        
        layout.addWidget(QLabel("总波形数量:"), 1, 0)
        self.total_waveforms_label = QLabel("0")
        layout.addWidget(self.total_waveforms_label, 1, 1)
        
        group.setLayout(layout)
        parent_layout.addWidget(group)
    
    def create_mode_group(self, parent_layout):
        """创建模式选择组"""
        group = QGroupBox("绘图模式")
        layout = QGridLayout()
        
        self.plot_mode1_group = self._create_radio_group(["A/P", "I/Q"], layout, 0)
        self.plot_mode2_group = self._create_radio_group(["Wave", "FFT"], layout, 1)
        self.plot_mode3_group = self._create_radio_group(["Plot", "Save Figure"], layout, 2)
        
        group.setLayout(layout)
        parent_layout.addWidget(group, 0, 0)
        
    def _create_radio_group(self, options, layout, row, default=None):
        """创建单选按钮组的辅助方法"""
        button_group = QButtonGroup(self)
        for i, option in enumerate(options):
            radio = QRadioButton(option)
            button_group.addButton(radio)
            layout.addWidget(radio, row, i)
            if (default and option == default) or (not default and i == 0):
                radio.setChecked(True)
        return button_group
    
    def create_plot_style_group(self, parent_layout):
        """创建绘图样式组"""
        group = QGroupBox("绘图样式")
        layout = QGridLayout()
        
        # 字体大小、线宽、图形尺寸
        self.font_size_combo = self._add_combo(
            layout, "字体", 0, config.FONT_SIZE_OPTIONS, config.DEFAULT_FONT_SIZE
        )
        self.linewidth_combo = self._add_combo(
            layout, "线宽", 1, config.LINE_WIDTH_OPTIONS, config.DEFAULT_LINE_WIDTH
        )
        self.figsize_w_combo = self._add_combo(
            layout, "图宽", 2, config.FIGURE_WIDTH_OPTIONS, config.DEFAULT_FIGURE_WIDTH
        )
        self.figsize_h_combo = self._add_combo(
            layout, "图高", 3, config.FIGURE_HEIGHT_OPTIONS, config.DEFAULT_FIGURE_HEIGHT
        )
        
        # 对数Y轴选项
        self.plot_style_logy = QCheckBox("对数Y轴")
        layout.addWidget(self.plot_style_logy, 4, 1)
        
        group.setLayout(layout)
        parent_layout.addWidget(group, 0, 1)
        
    def _add_combo(self, layout, label, row, items, default):
        """添加下拉框的辅助方法"""
        layout.addWidget(QLabel(label), row, 0)
        combo = QComboBox()
        combo.addItems(items)
        combo.setCurrentText(default)
        layout.addWidget(combo, row, 1)
        return combo
    
    def create_command_group(self, parent_layout):
        """创建命令按钮组"""
        group = QGroupBox("操作")
        layout = QVBoxLayout()
        
        plot_button = QPushButton("绘制数据")
        plot_button.clicked.connect(self.plot_data)
        layout.addWidget(plot_button)
        
        preview_button = QPushButton("预览文件信息")
        preview_button.clicked.connect(self.preview_data)
        layout.addWidget(preview_button)
        
        group.setLayout(layout)
        parent_layout.addWidget(group, 1, 0, 1, 2)

    def create_batch_processing_group(self, parent_layout):
        """创建批量处理组"""
        group = QGroupBox("批量处理")
        group.setCheckable(True)
        group.setChecked(False)
        layout = QGridLayout()

        layout.addWidget(QLabel("起始索引:"), 0, 0)
        self.start_index_spinbox = QSpinBox()
        self.start_index_spinbox.setMinimum(0)
        self.start_index_spinbox.setMaximum(0)
        layout.addWidget(self.start_index_spinbox, 0, 1)

        layout.addWidget(QLabel("结束索引:"), 1, 0)
        self.end_index_spinbox = QSpinBox()
        self.end_index_spinbox.setMinimum(0)
        self.end_index_spinbox.setMaximum(0)
        layout.addWidget(self.end_index_spinbox, 1, 1)

        group.setLayout(layout)
        parent_layout.addWidget(group)

        # Connect signals
        group.toggled.connect(self.on_batch_processing_toggled)
        self.start_index_spinbox.valueChanged.connect(self.on_start_index_changed)

        # Store the groupbox and disable it by default
        self.batch_processing_group = group
        self.on_batch_processing_toggled(False)
        
    def create_parameter_group(self, parent_layout):
        """创建参数设置组"""
        group = QGroupBox("时间和频率设置")
        layout = QGridLayout()
        
        self.sampling_freq_edit = self._add_param(layout, "采样频率", 0, str(config.DEFAULT_SAMPLING_FREQ), "[MHz]")
        self.time_unit_combo = self._add_combo(layout, "时间单位", 1, config.TIME_UNIT_OPTIONS, "[us]")
        self.t_start_edit = self._add_param(layout, "时间起始", 2, config.DEFAULT_TIME_START)
        self.t_end_edit = self._add_param(layout, "时间结束", 3, config.DEFAULT_TIME_END)
        self.freq_unit_combo = self._add_combo(layout, "频率单位", 4, config.FREQ_UNIT_OPTIONS, "[Hz]")
        self.f_start_edit = self._add_param(layout, "频率起始", 5, config.DEFAULT_FREQ_START)
        self.f_end_edit = self._add_param(layout, "频率结束", 6, config.DEFAULT_FREQ_END)
        self.p_min_edit = self._add_param(layout, "相位最小", 7, "", "[deg]")
        self.p_max_edit = self._add_param(layout, "相位最大", 8, "", "[deg]")
        
        group.setLayout(layout)
        parent_layout.addWidget(group)
        
    def _add_param(self, layout, label, row, default_val, unit=None):
        """添加参数输入框的辅助方法"""
        layout.addWidget(QLabel(label), row, 0)
        edit = QLineEdit(default_val)
        layout.addWidget(edit, row, 1)
        if unit:
            layout.addWidget(QLabel(unit), row, 2)
        return edit
    
    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        file_menu = menubar.addMenu('文件(&F)')
        
        load_action = file_menu.addAction('加载HDF5文件(&L)...')
        load_action.setShortcut(config.MENU_SHORTCUTS['load_files'])
        load_action.triggered.connect(self.load_file)
        
        file_menu.addSeparator()
        
        preview_action = file_menu.addAction('预览文件信息(&P)')
        preview_action.triggered.connect(self.preview_data)
        
        file_menu.addSeparator()
        
        exit_action = file_menu.addAction('退出(&E)')
        exit_action.setShortcut(config.MENU_SHORTCUTS['exit'])
        exit_action.triggered.connect(self.close)
        
        help_menu = menubar.addMenu('帮助(&H)')
        about_action = help_menu.addAction('关于(&A)')
        about_action.triggered.connect(
            lambda: QMessageBox.about(self, "关于", config.APP_ABOUT_TEXT)
        )
    
    def load_file(self):
        """加载HDF5文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择HDF5文件", "", 
            f"HDF5文件 ({' '.join(config.HDF5_EXTENSIONS)});;所有文件 (*)"
        )
        
        if file_path:
            self.current_file_path = file_path
            self.filename_display.setText(os.path.basename(file_path))
            self.file_loaded.emit(file_path)
    
    def update_file_tree(self, file_structure):
        """更新文件结构树"""
        self.file_tree.clear()
        if file_structure:
            self._populate_tree_item(self.file_tree.invisibleRootItem(), file_structure)
            self.file_tree.expandAll()
    
    def _populate_tree_item(self, parent_item, node):
        """递归填充树形结构"""
        if node['type'] == 'root':
            # 根节点，处理子节点
            if 'children' in node:
                for child in node['children']:
                    self._populate_tree_item(parent_item, child)
        else:
            # 创建树形项目
            item = QTreeWidgetItem(parent_item)
            item.setText(0, node['name'])
            item.setText(1, node['type'])
            
            if node['type'] == 'dataset':
                item.setText(2, str(node.get('shape', '')))
                item.setText(3, str(node.get('dtype', '')))
                size_mb = node.get('nbytes', 0) / (1024 * 1024)
                item.setText(4, f"{size_mb:.2f} MB")
                
                # 存储完整路径信息
                item.setData(0, Qt.UserRole, node.get('path', ''))
            
            # 处理子节点
            if 'children' in node:
                for child in node['children']:
                    self._populate_tree_item(item, child)
    
    def update_amp_phase_pairs(self, pairs):
        """更新幅度-相位配对列表"""
        self.amp_phase_pairs = pairs
        # 保存原始顺序
        self.original_pairs_order = pairs.copy()
        self.pairs_tree.clear()
        
        for pair in pairs:
            item = QTreeWidgetItem(self.pairs_tree)
            item.setText(0, pair['base_name'])
            
            # 添加复选框
            checkbox = QCheckBox()
            checkbox.setChecked(True)  # 默认选中
            self.pairs_tree.setItemWidget(item, 1, checkbox)
            
            # 存储配对信息
            item.setData(0, Qt.UserRole, pair)
        
        # 更新波形选择器
        if pairs:
            # 假设所有配对的波形数相同，取第一个的信息
            first_pair = pairs[0]
            amp_dataset = first_pair['amp_dataset']
            if 'shape' in amp_dataset and len(amp_dataset['shape']) > 1:
                max_waveform = amp_dataset['shape'][0] - 1
                self.waveform_spinbox.setMaximum(max_waveform)
                self.total_waveforms_label.setText(str(max_waveform + 1))

                # 更新批量处理控件
                self.start_index_spinbox.setMaximum(max_waveform)
                self.end_index_spinbox.setMaximum(max_waveform)
                self.end_index_spinbox.setMinimum(self.start_index_spinbox.value())
            else:
                self.waveform_spinbox.setMaximum(0)
                self.total_waveforms_label.setText("1")
                # Also reset batch controls
                self.start_index_spinbox.setMaximum(0)
                self.end_index_spinbox.setMaximum(0)
        else:
            self.waveform_spinbox.setMaximum(0)
            self.total_waveforms_label.setText("1")
            self.start_index_spinbox.setMaximum(0)
            self.end_index_spinbox.setMaximum(0)

    def on_batch_processing_toggled(self, checked):
        """批量处理组复选框状态改变时的槽函数"""
        self.waveform_spinbox.setEnabled(not checked)
        if checked:
            self.end_index_spinbox.setValue(self.end_index_spinbox.maximum())

    def on_start_index_changed(self, value):
        """起始索引改变时，更新结束索引的最小值"""
        self.end_index_spinbox.setMinimum(value)
    
    def auto_sort_pairs(self):
        """发射自动排序信号"""
        self.sorting_requested.emit()
    
    def find_amp_phase_pairs(self):
        """
        在文件结构树中自动查找并配对 幅度/相位 数据对
        """
        if not self.current_file_path:
            QMessageBox.warning(self, "警告", "请先加载HDF5文件")
            return
        
        # 发射信号，让数据处理器处理
        # 这里暂时显示消息，实际处理在数据处理器中
        QMessageBox.information(self, "信息", "正在查找幅度-相位配对...")
    
    def preview_data(self):
        """预览数据"""
        if not self.current_file_path:
            QMessageBox.warning(self, "警告", "请先加载HDF5文件")
            return
        self.preview_requested.emit()
    
    def plot_data(self):
        """绘制数据"""
        if not self.current_file_path:
            QMessageBox.warning(self, "警告", "请先加载HDF5文件")
            return
        
        # 获取选中的数据对
        selected_pairs = []
        for i in range(self.pairs_tree.topLevelItemCount()):
            item = self.pairs_tree.topLevelItem(i)
            checkbox = self.pairs_tree.itemWidget(item, 1)
            if checkbox and checkbox.isChecked():
                pair_data = item.data(0, Qt.UserRole)
                selected_pairs.append(pair_data)
        
        if not selected_pairs:
            QMessageBox.warning(self, "警告", "请选择要绘制的数据对")
            return
        
        # 收集所有参数
        parameters = self.get_plot_parameters()
        parameters['selected_pairs'] = selected_pairs
        
        batch_enabled = self.batch_processing_group.isChecked()
        parameters['batch_enabled'] = batch_enabled
        
        if batch_enabled:
            parameters['start_index'] = self.start_index_spinbox.value()
            parameters['end_index'] = self.end_index_spinbox.value()
        else:
            parameters['waveform_index'] = self.waveform_spinbox.value()
        
        self.plot_requested.emit(parameters)
    
    def get_plot_parameters(self):
        """获取绘图参数"""
        return {
            'file_path': self.current_file_path,
            'plot_mode': self.plot_mode1_group.checkedButton().text(),
            'wave_or_fft': self.plot_mode2_group.checkedButton().text(),
            'plot_or_save': 'Save' if self.plot_mode3_group.checkedButton().text() == 'Save Figure' else 'Plot',
            'log_y': self.plot_style_logy.isChecked(),
            'font_size': int(self.font_size_combo.currentText()),
            'line_width': float(self.linewidth_combo.currentText()),
            'figure_size': (int(self.figsize_w_combo.currentText()), int(self.figsize_h_combo.currentText())),
            'time_unit': self.time_unit_combo.currentText(),
            'freq_unit': self.freq_unit_combo.currentText(),
            'sampling_freq': self.sampling_freq_edit.text(),
            't_start': self.t_start_edit.text(),
            't_end': self.t_end_edit.text(),
            'f_start': self.f_start_edit.text(),
            'f_end': self.f_end_edit.text(),
            'p_min': self.p_min_edit.text(),
            'p_max': self.p_max_edit.text()
        }
    
    def set_sampling_freq(self, freq):
        """设置采样频率"""
        self.sampling_freq_edit.setText(str(freq))
    
    def show_preview_info(self, preview_text):
        """显示预览信息"""
        QMessageBox.information(self, "文件预览", preview_text)
        
    def show_error_message(self, title, message):
        """显示错误消息"""
        QMessageBox.critical(self, title, message)
        
    def show_info_message(self, title, message):
        """显示信息消息"""
        QMessageBox.information(self, title, message)
        
    def show_warning_message(self, title, message):
        """显示警告消息"""
        QMessageBox.warning(self, title, message)
    
    def toggle_drag_sort(self, checked):
        """切换拖拽排序模式"""
        self.pairs_tree.setDragEnabled(checked)
        if checked:
            self.enable_drag_sort_button.setText("禁用拖拽排序")
            self.show_info_message("拖拽排序", "拖拽排序已启用，您可以直接拖拽数据对来重新排序")
        else:
            self.enable_drag_sort_button.setText("启用拖拽排序")
    
    def move_pair_up(self):
        """将选中的数据对向上移动"""
        current_item = self.pairs_tree.currentItem()
        if not current_item:
            self.show_warning_message("警告", "请先选择要移动的数据对")
            return
        
        current_index = self.pairs_tree.indexOfTopLevelItem(current_item)
        if current_index > 0:
            # 获取当前项的复选框状态
            current_checkbox = self.pairs_tree.itemWidget(current_item, 1)
            current_checked = current_checkbox.isChecked() if current_checkbox else True
            
            # 获取上一项的复选框状态
            prev_item = self.pairs_tree.topLevelItem(current_index - 1)
            prev_checkbox = self.pairs_tree.itemWidget(prev_item, 1)
            prev_checked = prev_checkbox.isChecked() if prev_checkbox else True
            
            # 交换位置
            self.pairs_tree.takeTopLevelItem(current_index)
            self.pairs_tree.insertTopLevelItem(current_index - 1, current_item)
            
            # 重新创建复选框
            new_current_checkbox = QCheckBox()
            new_current_checkbox.setChecked(current_checked)
            self.pairs_tree.setItemWidget(current_item, 1, new_current_checkbox)
            
            new_prev_checkbox = QCheckBox()
            new_prev_checkbox.setChecked(prev_checked)
            self.pairs_tree.setItemWidget(prev_item, 1, new_prev_checkbox)
            
            # 重新设置当前选中项
            self.pairs_tree.setCurrentItem(current_item)
            
            # 更新内部数据顺序
            self._update_pairs_order()
    
    def move_pair_down(self):
        """将选中的数据对向下移动"""
        current_item = self.pairs_tree.currentItem()
        if not current_item:
            self.show_warning_message("警告", "请先选择要移动的数据对")
            return
        
        current_index = self.pairs_tree.indexOfTopLevelItem(current_item)
        if current_index < self.pairs_tree.topLevelItemCount() - 1:
            # 获取当前项的复选框状态
            current_checkbox = self.pairs_tree.itemWidget(current_item, 1)
            current_checked = current_checkbox.isChecked() if current_checkbox else True
            
            # 获取下一项的复选框状态
            next_item = self.pairs_tree.topLevelItem(current_index + 1)
            next_checkbox = self.pairs_tree.itemWidget(next_item, 1)
            next_checked = next_checkbox.isChecked() if next_checkbox else True
            
            # 交换位置
            self.pairs_tree.takeTopLevelItem(current_index)
            self.pairs_tree.insertTopLevelItem(current_index + 1, current_item)
            
            # 重新创建复选框
            new_current_checkbox = QCheckBox()
            new_current_checkbox.setChecked(current_checked)
            self.pairs_tree.setItemWidget(current_item, 1, new_current_checkbox)
            
            new_next_checkbox = QCheckBox()
            new_next_checkbox.setChecked(next_checked)
            self.pairs_tree.setItemWidget(next_item, 1, new_next_checkbox)
            
            # 重新设置当前选中项
            self.pairs_tree.setCurrentItem(current_item)
            
            # 更新内部数据顺序
            self._update_pairs_order()
    
    def reset_pairs_order(self):
        """重置数据对顺序到原始状态"""
        if not self.original_pairs_order:
            self.show_warning_message("警告", "没有原始顺序可重置")
            return
        
        # 重新填充树，使用原始顺序
        self.pairs_tree.clear()
        for pair in self.original_pairs_order:
            item = QTreeWidgetItem(self.pairs_tree)
            item.setText(0, pair['base_name'])
            
            # 添加复选框
            checkbox = QCheckBox()
            checkbox.setChecked(True)  # 默认选中
            self.pairs_tree.setItemWidget(item, 1, checkbox)
            
            # 存储配对信息
            item.setData(0, Qt.UserRole, pair)
        
        # 恢复原始数据顺序
        self.amp_phase_pairs = self.original_pairs_order.copy()
        
        self.show_info_message("重置完成", "数据对顺序已重置到原始状态")
    
    def _on_pairs_reordered(self, parent, start, end, destination, row):
        """处理数据对重新排序事件"""
        # 使用QTimer.singleShot延迟更新，避免在拖拽操作期间直接修改模型导致的不稳定
        QTimer.singleShot(0, self._update_pairs_order)

    def _update_pairs_order(self):
        """根据当前树形控件中的顺序更新内部数据顺序"""
        new_order = []
        
        # 重新创建所有复选框，以防拖拽操作丢失widget
        for i in range(self.pairs_tree.topLevelItemCount()):
            item = self.pairs_tree.topLevelItem(i)
            pair_data = item.data(0, Qt.UserRole)
            if pair_data:
                new_order.append(pair_data)
            
            # 检查是否有复选框，如果没有则重新创建
            checkbox = self.pairs_tree.itemWidget(item, 1)
            if not checkbox:
                new_checkbox = QCheckBox()
                new_checkbox.setChecked(True)  # 默认选中
                self.pairs_tree.setItemWidget(item, 1, new_checkbox)
        
        self.amp_phase_pairs = new_order 